-- 删除秒杀活动数据脚本
-- 参数说明:
-- ARGV[1]: 活动ID
-- 
-- 返回值说明:
-- 返回删除的Redis键总数，包括库存数据、用户限制、购买记录、订单数据等所有相关键

local activityId = ARGV[1]
local deletedCount = 0

-- 1. 删除库存数据
local stockPattern = 'seckill:activity:stock:' .. activityId .. ':*'
local stockKeys = redis.call('keys', stockPattern)
if #stockKeys > 0 then
    deletedCount = deletedCount + redis.call('del', unpack(stockKeys))
end

-- 2. 删除用户限制数据
local limitPattern = 'seckill:activity:limit:' .. activityId .. ':*'
local limitKeys = redis.call('keys', limitPattern)
if #limitKeys > 0 then
    deletedCount = deletedCount + redis.call('del', unpack(limitKeys))
end

-- 3. 删除用户购买记录
local purchasedPattern = 'seckill:activity:purchased:' .. activityId .. ':*'
local purchasedKeys = redis.call('keys', purchasedPattern)
if #purchasedKeys > 0 then
    deletedCount = deletedCount + redis.call('del', unpack(purchasedKeys))
end

-- 4. 删除商品列表
local productListKey = 'seckill:activity:products:' .. activityId
if redis.call('exists', productListKey) == 1 then
    deletedCount = deletedCount + redis.call('del', productListKey)
end

-- 5. 删除订单映射数据（需要先获取所有订单号）
local orderMappingPattern = 'seckill:activity:order:mapping:' .. activityId .. ':*'
local orderMappingKeys = redis.call('keys', orderMappingPattern)

if #orderMappingKeys > 0 then
    -- 遍历所有订单映射，删除订单记录
    for _, mappingKey in ipairs(orderMappingKeys) do
        local orderNos = redis.call('smembers', mappingKey)
        if #orderNos > 0 then
            for _, orderNo in ipairs(orderNos) do
                local orderKey = 'seckill:activity:order:' .. orderNo
                if redis.call('exists', orderKey) == 1 then
                    deletedCount = deletedCount + redis.call('del', orderKey)
                end
            end
        end
    end
    -- 删除所有映射键
    deletedCount = deletedCount + redis.call('del', unpack(orderMappingKeys))
end

return deletedCount